package com.ardo.entity;

import com.alibaba.fastjson.JSONObject;
import com.ardo.execption.code.ErrorCode;
import lombok.Data;

import java.io.Serializable;

@Data
public class ResponseResult<T> implements Serializable {


    //请求成功返回码
    private static final int successCode = 200;

    //返回数据
    private T data;

    //返回码
    private int code;

    //返回描述
    private String msg;

    public ResponseResult() {
        this.code = successCode;
        this.msg = "";
    }

    public ResponseResult(String msg) {
        this.code = successCode;
        this.msg = msg;
    }

    public ResponseResult(T data) {
        this();
        this.data = data;
    }

    public ResponseResult(ErrorCode errorCode) {
        this.code = errorCode.getCode();
        this.msg = errorCode.getMessage();
    }

    public ResponseResult(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public ResponseResult(int code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    /**
     * 操作成功 data为null
     */
    public static ResponseResult success() {
        return new ResponseResult();
    }

    /**
     * 操作成功 data为null，自定义msg
     */
    public static ResponseResult success(String msg) {
        return new ResponseResult(msg);
    }

    /**
     * 操作成功 data 不为null
     */
    public static ResponseResult success(Object data) {
        return new ResponseResult(data);
    }

    /**
     * 操作失败 data 不为null
     */
    public static ResponseResult failure(ErrorCode errorCode) {
        return new ResponseResult(errorCode);
    }

    /**
     * 自定义返回  data为null
     */
    public static ResponseResult failure(int code, String msg) {
        return new ResponseResult(code, msg);
    }

    public boolean isSuccess() {
        return this.code == successCode;
    }


    public String toJson() {
        return JSONObject.toJSONString(this);
    }
}
